import { createApp, toRaw } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia, PiniaPluginContext } from 'pinia'

//定义兜底变量
const __piniaKey = '__PINIAKEY__'

//定义入参类型
type Options = {
    key?: string
}

//将数据存在本地
const setStorage = (key: string, value: any): void => {
    localStorage.setItem(key, JSON.stringify(value))
}

//存缓存中读取
const getStorage = (key: string) => {
    return (localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {})
}

//利用函数柯丽华接受用户入参
const piniaPlugin = (options: Options) => {
    //将函数返回给pinia  让pinia  调用 注入 context
    return (context: PiniaPluginContext) => {
        const { store } = context;
        //                                       没有即默认值
        const data = getStorage(`${options?.key ?? __piniaKey}-${store.$id}`)
        store.$subscribe(() => {
            setStorage(`${options?.key ?? __piniaKey}-${store.$id}`, toRaw(store.$state));
        })

        //返回值覆盖pinia 原始值
        return {
            ...data
        }

    }

}

//初始化pinia
const pinia = createPinia()

//注册pinia 插件
pinia.use(piniaPlugin({
    key: "pinia"
}))


createApp(App).use(pinia).use(piniaPlugin).mount('#app')
